import {View, Text} from "@tarojs/components";
import {Cell, Empty, Grid, GridItem, Icon, Image, Search, Tag} from "@antmjs/vantui";
import Utils from "@/utils/common";
import React, {useCallback, useEffect, useRef, useState} from "react";
import {HotWordModel, ProjectModel} from "@/common/apis/model";
import {activityWordsApi, projectSearchApi} from "@/common/apis/home_datasource";

import RouthPath from "@/common/RouthPath";
import LocalUtils from "@/utils/local_utils";
import AssetImage from "@/common/AssetImage";

definePageConfig({
  navigationBarTitleText: '项目搜索',
})

export default function Search_project() {

  const [items, setItems] = useState<ProjectModel[]>()
  const inputKey = useRef('');

  const [showResult, setShowResult] = useState(false)


  const updateHistory = useCallback((keyword: string) => {
    // 只需一行代码
    LocalUtils.addHistoryItem(keyword);
    // 更新 state 以立即在UI上看到变化
    setHistoryList(LocalUtils.getHistoryList());
  }, []);

  const searchAction = useCallback((e) => {
    if (!Utils.isNotBlank(e.detail)) {
      Utils.showErrorToast('请输入搜索项目名')
      return;
    }
    if (e.detail === inputKey.current) {
      return;
    }
    inputKey.current = e.detail;
    projectSearchApi(inputKey.current).then((res) => {
      updateHistory(inputKey.current);
      if (res) {
        setShowResult(true)
        res.forEach(item => {
          if (item.note) {
            item.needs = item.note
            item.note =''
          }
        })
        setItems(res)
      }
    })
  }, [updateHistory]);
  const [historyList, setHistoryList] = useState<string[]>([]);
  const [hotList, setHotList] = useState<string[]>([]);


  const handleClearHistory = useCallback(() => {
    LocalUtils.clearHistoryList();
    setHistoryList([]);
  }, []);

  const handleTagClick = useCallback((keyword: string) => {
    searchAction({detail: keyword});
  }, [searchAction]);

  const renderPreSearch = useCallback(() => (
    <View style={{padding: '10px'}}>
      {hotList.length > 0 && (
        <View>
          <Text style={{fontWeight: 'bold'}}>热门搜索🔥</Text>
          <View style={{marginTop: '5px'}}>
            {hotList.map(item => (
              <Tag key={item} color='white' round textColor='black' size='large' onClick={() => handleTagClick(item)} style={{marginRight: '5px',padding:'5px 10px',minWidth:"40px",textAlign:"center",  display: 'inline-block',}}>
                {item}
              </Tag>
            ))}
          </View>
        </View>
      )}

      {/* 搜索历史 */}
      {historyList.length > 0 && (
        <View style={{marginTop: '10px'}}>
          <View style={{
            display: 'flex',
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginTop: '5px'
          }}>
            <Text style={{fontWeight: 'bold'}}>搜索历史</Text>
            <Icon name='delete-o' size='24px' color='#999' onClick={handleClearHistory}/>
          </View>
          <View>
            {historyList.map(item => (
              <Tag key={item} color='white' round textColor='black' size='large' onClick={() => handleTagClick(item)} style={{marginRight: '5px',padding:'5px 10px',minWidth:"40px",textAlign:"center",  display: 'inline-block',}}>
                {item}
              </Tag>
            ))}
          </View>
        </View>
      )}
    </View>
  ), [handleClearHistory, handleTagClick, historyList,hotList]);

  useEffect(() => {
    activityWordsApi().then((res) => {
      if (res) {
        const names = res?.map((item) => item.name)??[]
        console.log("names",names)
        setHotList(names)
      }
    })
    setHistoryList(LocalUtils.getHistoryList());
  }, []);

  const renderContent = useCallback(() => {
    if (Utils.isEmpty(items)) {
      return <Empty description='暂无数据'/>
    }
    return (<Grid border={false} columnNum={2}>
      {
        items?.map((item, index) => <GridItem forItem='index' key={index} onClick={() => {
          Utils.navigateTo({
            url: Utils.getUrlWithObject(RouthPath.projectDetail, {
              projectId: item
            }),
          })
        }}
        >
          <View style={{display: 'flex', flexDirection: 'column', overflow: 'hidden', width: '100%',}}>
            <Image src={item.image} style={{width: '100%', height: '140px'}}/>
            <Cell renderTitle={<View style={{display: 'flex', flexDirection: 'row', justifyContent: 'space-between'}}>
              <Text style={{fontSize: '14px', color: 'black'}}>{item.name}</Text>
              {/*<Text style={{fontSize: '12px', color: 'red'}}>{ShowUtils.getDefaultPrice(item.price)}</Text>*/}
              <View></View>
            </View>} label={item.note}
            />
          </View>
        </GridItem>)
      }
    </Grid>)
  }, [items]);

  return (
    <View style={{display: 'flex', flexDirection: 'column', height: '100vh', backgroundColor: AssetImage.bg}}>
      <View>
        <Search
          placeholder='请输入搜索项目名称'
          onSearch={searchAction}
        />
      </View>
      <View style={{flex: 1}}>
        {
          showResult ? null : renderPreSearch()
        }
        {
          showResult && renderContent()
        }
      </View>
    </View>
  )
}




